<template>
  <div>
    <div class="search">

      <p> 角色名称</p>
      <el-input v-model="keyword" placeholder="请输入角色关键字" @keydown.enter.native="renderRoleList"></el-input>

      <el-button type="primary" @click="renderRoleList()" size="small">搜索</el-button>
      <el-button type="primary" @click="handleAdd" size="small">新增</el-button>

    </div>

    <el-table :data="tableData" border class="table" :height="getHeight()" style="margin-left: 20px; width: 95% ">
      <el-table-column type="index" label="序号" width="50" align="center" fixed>
      </el-table-column>

      <el-table-column prop="id" label="ID" width="100" align="center">
      </el-table-column>
      <el-table-column prop="name" label="名称" width="200" align="center">
      </el-table-column>
      <el-table-column prop="desc" label="描述" align="center">
      </el-table-column>
      <el-table-column prop="created_at" label="创建时间" width="200" align="center">
      </el-table-column>
      <el-table-column prop="updated_at" label="更新时间" width="200" align="center">
      </el-table-column>

      <el-table-column label="操作" width="200" align="center" fixed="right">
        <template slot-scope="scope">

          <el-button type="primary" icon="el-icon-edit" circle size="small" @click="editRow(scope.row)"></el-button>
          <el-button @click="detailRow(scope.row)" type="warning" icon="el-icon-key" circle size="small"></el-button>
          <el-button @click.native.prevent="deleteRow(scope.row)" type="danger" icon="el-icon-delete" circle size="small"
            class="delbtn"> </el-button>

        </template>
      </el-table-column>
    </el-table>

    <!-- 分页 -->
    <el-row class="footer" style="margin: 20px;">
      <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="page"
        :page-sizes="[5, 10, 15, 20]" :page-size="limit" layout="total, sizes, prev, pager, next,jumper" :total="count">
      </el-pagination>
    </el-row>

    <!-- 添加编辑对话框 -->
    <el-dialog :title="title" :visible.sync="dialogFormVisible" @close="form = {}">
      <el-form :model="form" label-width='90px' :rules="rules" ref="ruleForm" v-if="isShow1">
        <el-form-item label="角色名称" prop="name">
          <el-input v-model="form.name" placeholder="请输入角色名称"></el-input>
        </el-form-item>
        <el-form-item label="角色描述" prop="desc">
          <el-input v-model="form.desc" placeholder="请输入角色描述"></el-input>
        </el-form-item>
      </el-form>

      <el-form v-if="isShow2" >
        
        <el-tree :data="roleArr" show-checkbox node-key="id" :default-expanded-keys="defaultChecked" :default-checked-keys="defaultChecked"
          :props="defaultProps" ref="tree">
        </el-tree>
    
      </el-form>

      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="dialogFormVisible = false; onSubmit()">确 定</el-button>
      </div>
    </el-dialog>

  </div>
</template>
  
<script>
import { getRoleList, addRole, delRole, editRole, addRolePermission,delRolePermission,getPermissionList } from '@/api/role'

export default {
  name: 'roleManagement',
  data() {
    return {
      keyword: "",
      tableData: [],
      page: 1,
      limit: 20,
      count: 0,
      form: {},
      title: '添加角色',
      dialogFormVisible: false,
      isShow1: true,
      isShow2: false,
      rules: {
        name: [
          { required: true, message: '请输入角色名称', trigger: 'blur' },
        ],
        desc: [
          { required: true, message: '请输入角色描述', trigger: 'blur' },

        ],
      },
      defaultChecked:[],
      roleArr: [],
        defaultProps: {
          children: 'children',
          label: 'label'
        },
        curId:'',
        permission_ids:[]
    }
  },
  created() {
    this.renderRoleList()
  },

  methods: {
    renderRoleList() {
      getRoleList({ keyword: this.keyword, page: this.page, limit: this.limit }).then(res => {
        if (res.code == 1) {
          //console.log(res)
          this.tableData = res.data.list
          this.count = res.data.count
        }
      })
    },

    handleSizeChange(val) {
      this.limit = val
      this.renderRoleList()
    },
    //改变当前页
    handleCurrentChange(val) {
      this.page = val
      this.renderRoleList()
    },
    //获取表格高度
    getHeight() {
      return window.innerHeight - 255
    },

    // 打开编辑数据回显
    editRow(row) {
      this.isShow1 = true
      this.isShow2 = false
      this.dialogFormVisible = true
      this.title = '编辑角色',
      this.form = { ...row }
    },
    //打开添加
    handleAdd() {
      this.isShow1 = true
      this.isShow2 = false
      this.dialogFormVisible = true
      this.title = '添加角色'
    },
    //打开分配权限 权限数据回显
    detailRow(row) {
      this.isShow2 = true
      this.isShow1 = false
      this.dialogFormVisible = true
      this.title = '分配权限 : '+row.name
      this.curId=row.id
      //获取权限 转为树形结构
      getPermissionList({keyword:'',limit:100,page:1}).then(res=>{
        if(res.code==1){
         // console.log(res.data.list)
          let arr1=res.data.list.map(item=>{
              return{
                level:item.path.split('/').length-1,
                id:item.id,
                label:item.name,
                path:item.path,
                children:[],
              }
          })
       // console.log(arr1)
        this.roleArr=arr1.filter(item=>{
        arr1.forEach(el=>{
          if(el.level-item.level==1 && el.path.includes(item.path)) {
            item.children.push(el)
          }
        })
        return item.level==1
       })
     //  console.log(this.roleArr)
        }
      })

      //权限数据回显
     this.defaultChecked= row.permissions && row.permissions.map(item=>{
       return item.id
      })
    //  console.log(this.defaultChecked)
      
    },
    
    //判断是添加还是编辑
    onSubmit() {
      if (this.title == '添加角色') {
        this.add()
      } else if(this.title=='编辑角色'){
        this.edit()
      }else{
        this.handlePermission()
      }
    },
   

    //编辑角色权限
    handlePermission(){
      //获取选中的id
      let checked_ids= this.$refs.tree.getCheckedKeys()
      //console.log(checked_ids)
    //  console.log(this.defaultChecked)
    let addArr=[]
     let delArr=[]
      //获取要添加的id
     if(checked_ids.length!=0){
      this.defaultChecked=this.defaultChecked||[]
      addArr=checked_ids.filter(item=>{
        return this.defaultChecked.indexOf(item)==-1
      })
     }

      //获取需要删除的id
      if(this.defaultChecked){
      delArr= this.defaultChecked.filter((item)=>{
         return checked_ids.indexOf(item)==-1
     })
  
      }
     if(delArr.length!=0){
      delRolePermission({role_id:this.curId,permission_ids:delArr}).then(res=>{
      if(res.code==1){ 
        this.$message.success('权限删除成功')
        this.renderRoleList()
      }
     })
     }
     
     if(addArr.length!=0){
      addRolePermission({role_id:this.curId,permission_ids:addArr}).then(res=>{
      if(res.code==1){
        this.$message.success('权限添加成功')
        this.renderRoleList() 
      }
     })
     }
     },
    
    //添加角色
    add() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          addRole(this.form).then(res => {
            if (res.code == 1) {
              this.$message.success('添加成功')
              this.renderRoleList()
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    // 编辑角色
    edit() {
      this.$refs.ruleForm.validate((valid) => {
        if (valid) {
          editRole(this.form).then(res => {
            if (res.code == 1) {
              this.$message.success('编辑成功')
              this.renderRoleList()
            }
          })
        } else {
          console.log('error submit!!');
          return false;
        }
      });
    },
    //删除
    deleteRow(row) {
      delRole(row).then(res => {
        if (res.code == 1) {
          this.$message.success('删除成功')
          this.renderRoleList()
        }
      })
    },

  },
}

</script>  
  
<style  scoped>
.search {
  display: flex;
  padding: 20px;
  box-sizing: border-box;
  align-items: center;
}

.search p {
  width: 80px;
}

.search .el-input {
  width: 200px;
  margin-right: 20px;
}
</style>
  